package com.maimao.search.config;

import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * @author MaoLin Wang
 * @date 2020/12/26 8:27 下午
 */
@Configuration
public class ElasticSearchConfig {

    @Value("${maimao.es.hosts}")
    private String hosts;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        //解析hostlist配置信息
        String[] hostList = hosts.split(",");
        //创建HttpHost数组，其中存放es主机和端口的配置信息
        HttpHost[] httpHostArray = new HttpHost[hostList.length];
        for (int i = 0; i < hostList.length; i++) {
            String host = hostList[i];
            String[] hostSplit = host.split(":");
            httpHostArray[i] = new HttpHost(hostSplit[0], Integer.parseInt(hostSplit[1]), "http");
        }
        //创建RestHighLevelClient客户端
        return new RestHighLevelClient(RestClient.builder(httpHostArray)
                // TODO
                .setHttpClientConfigCallback(config -> config.setKeepAliveStrategy(((response, context) -> TimeUnit.MINUTES.toMillis(3))))
                .setRequestConfigCallback(builder -> {
                    return builder.setConnectTimeout(30 * 1000) // 连接超时（默认为1秒）
                            .setSocketTimeout(60 * 1000);// 套接字超时（默认为30秒）//更改客户端的超时限制默认30秒现在改为100*1000分钟
                }));
    }


}
